package com.ooolong.expression.function.string;

import com.ooolong.expression.ExpressionException;
import com.ooolong.expression.OObject;
import com.ooolong.expression.function.Function;

public class CharAt extends Function {

	public CharAt() {
		super("charAt");
		argLength = 2;
		argTypeArray = new int[] { OObject.STRING, OObject.INTEGER };
	}

	@Override
	public OObject execute(OObject[] args) throws ExpressionException {
		checkArguments(args);

		OObject arg0 = args[0];
		OObject arg1 = args[1];
		if (arg0.getString() != null) {
			String s = arg0.getString();
			long index = arg1.toLong();
			if (index < 0 || index >= s.length()) {
				throw new ExpressionException();
			}
			char c = s.charAt((int) index);
			return OObject.newInstance(c);
		}
		throw new ExpressionException();
	}
}
